package com.hnichr.crm.biz.bill.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.hnichr.crm.common.bill.entity.CrmBill;
import com.hnichr.crm.common.bill.service.ICrmBillService;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.jpa.initiator.JpaUtilAble;
import com.mxpioframework.jpa.query.Criteria;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 开票Service业务层处理
 *
 * @author Cheng
 * @date 2022-12-24
 */
@Service
public class CrmBillServiceImpl implements ICrmBillService, JpaUtilAble {
    @Override
    public void afterPropertiesSet(ApplicationContext applicationContext) {

    }

    @Override
    @Transactional(readOnly = true)
    public Page<CrmBill> page(Criteria criteria, Pageable pageable) {
        return JpaUtil.linq(CrmBill.class).where(criteria).paging(pageable);
    }

    @Override
    @Transactional(readOnly = true)
    public CrmBill getById(String id) {
        return JpaUtil.linq(CrmBill.class).idEqual(id).findOne();
    }

    @Override
    @Transactional(readOnly = false)
    public void save(CrmBill crmBill) {
        String dateStr = DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN);
        long maxCount = getMaxCount();
        String seq = StringUtils.leftPad(String.valueOf(maxCount + 1), 4, "0");
        crmBill.setNum("B" + dateStr + seq);
        JpaUtil.save(crmBill);
    }

    @Override
    @Transactional(readOnly = false)
    public void update(CrmBill crmBill) {
        JpaUtil.update(crmBill);
    }

    @Override
    @Transactional(readOnly = false)
    public int delete(String id) {
        return JpaUtil.lind(CrmBill.class).equal("id", id).delete();
    }

    @Override
    @Transactional(readOnly = true)
    public long getMaxCount() {
        Date now = new Date();
        return JpaUtil.linq(CrmBill.class).between("createTime", DateUtil.beginOfDay(now), DateUtil.endOfDay(now)).count();
    }
}
